// Package models
// @Title  articleCatModel.go
// @Description  文章目录模型
// @Author  小斌 (时间 格式是2021/12/02  10:20)
// @Update  小斌 (时间 格式是2021/12/02  10:20)

package models

import (
	"github.com/astaxie/beego/orm"
	"time"
)

// ArticleCatObj 文章目录 实体类
type ArticleCatObj struct {
	Id                 int    `valid:"id"`
	CatName                string `valid:"cat_name"`
	Sort                int `valid:"sort"`
	Status				int `valid:"status"`
	IsDelete				int `valid:"is_delete"`
	UpdateTime                time.Time `valid:"update_time" orm:"auto_now"`
	AddTime                time.Time `valid:"add_time" orm:"auto_now_add"`
}

func (this *ArticleCatObj) TableName() string {
	return "article_cat"
}

func init() {
	orm.RegisterModel(new(ArticleCatObj))
}

// GetArticleCatList 获取分页数据
func GetArticleCatList(pageSize int, page int) (*[]ArticleCatObj, int, error) {
	var (
		list []ArticleCatObj
		err  error
	)
	qs := orm.NewOrm().QueryTable(new(ArticleCatObj)).OrderBy("-add_time")

	_, err = qs.Filter("is_delete",0).Limit(pageSize).Offset((page - 1) * pageSize).RelatedSel().All(&list)
	count, _ := qs.Filter("is_delete",0).Count()

	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return nil, 0, err
	}

	return &list, int(count), nil
}

// GetArticleCatInfoById 根据ID获取记录
func GetArticleCatInfoById(id int) (ArticleCatObj,error) {
	var (
		row ArticleCatObj
		err  error
	)

	err = orm.NewOrm().QueryTable(new(ArticleCatObj)).Filter("id", id).Filter("is_delete", 0).One(&row)
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return row,nil
	}

	return row,nil
}

// GetUseArticleCatList 获取启用的文章目录
func GetUseArticleCatList() (*[]ArticleCatObj,error) {
	var (
		list []ArticleCatObj
		err  error
	)
	qs := orm.NewOrm().QueryTable(new(ArticleCatObj)).OrderBy("-sort")

	_, err = qs.Filter("status",0).Filter("is_delete",0).Limit(10).Offset(0).RelatedSel().All(&list)
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return nil, err
	}

	return &list, nil
}

// AddArticleCat 添加文章目录
func AddArticleCat(catName string,status int) int64 {
	articleCat := ArticleCatObj{
		CatName:    catName,
		Status: status,
		IsDelete: 0,
	}

	id,err := orm.NewOrm().Insert(&articleCat)

	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return id
}

// UpdateArticleCatById 修改文章目录
func UpdateArticleCatById(id int,catName string,status int) int64 {
	articleCat := ArticleCatObj{
		Id:    id,
		CatName:    catName,
		Status: status,
	}
	num,err := orm.NewOrm().Update(&articleCat,"cat_name","status")

	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return num
}

// DeleteArticleCatById 删除文章目录
func DeleteArticleCatById(id int) int64 {
	articleCat := ArticleCatObj{
		Id:    id,
		IsDelete: 1,
	}
	num,err := orm.NewOrm().Update(&articleCat,"is_delete")
	if err == orm.ErrNoRows || err == orm.ErrMissPK {
		return 0
	}

	return num
}